package com.guoxianwei.scm.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.guoxianwei.scm.web.actions.AccountActionBean;

public class LoginFilter implements Filter {

	private static transient Log log = LogFactory.getLog(LoginFilter.class);

	private static Pattern PATTERN = Pattern
			.compile("document.cookie|href|script|select |select/|select\\(|select\\*|insert |insert/|insert\\(|insert\\*|update |update/|update\\(|update\\*|delete |delete/|delete\\(|delete\\*|truncate |truncate/|truncate\\(|truncate\\*|exec |exec/|exec\\(|exec\\*|drop |drop/|drop\\(|drop\\*");

	public void init(FilterConfig filterConfig) throws ServletException {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		HttpSession session = req.getSession(true);

		AccountActionBean actionBean = (AccountActionBean) session
				.getAttribute("accountBean");

		String url = StringUtils.substringAfter(req.getRequestURI().toString(),
				req.getContextPath());
		if (url.endsWith("Account.action")
				&& StringUtils.isNotBlank(req.getParameter("sec"))) {
			chain.doFilter(request, response);
		} else {
			if (actionBean == null || !actionBean.isAuthenticated()) {
				res.sendRedirect(req.getContextPath() + "/login.jsp ");
			} else {

				String query = req.getQueryString();
				if (!(StringUtils.isBlank(query))) {
					url = url + "?" + query;
				}

				if (((!(StringUtils.isBlank(query))) && (PATTERN
						.matcher(URLDecoder.decode(query.toLowerCase(), "UTF-8"))
						.find()))
						|| ((url.indexOf("//") > -1) && (checkDoubleSlash(url)))) {
					StringBuffer sb = new StringBuffer();
					sb.append("</p>");
					log.error(sb.toString());
					res.setContentType("text/html; charset=GBK");
					PrintWriter writer = res.getWriter();
					writer.print(sb.toString());
					return;
				}
				chain.doFilter(request, response);
			}
		}

	}

	private boolean checkDoubleSlash(String url) {
		boolean rtn = false;
		if (url.indexOf("//") > -1) {
			String urlNew = StringUtils.replace(url, "http://", "");
			if (urlNew.indexOf("//") > -1) {
				rtn = true;
			}
		}
		return rtn;
	}

	public void destroy() {
	}
}
